package com.xinnet.mms.web;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.area.service.AreaService;
import com.xinnet.mms.cart.service.ShopCartService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.Role;
import com.xinnet.mms.entity.ShopCart;
import com.xinnet.mms.enums.CustomerTypeEnmu;
import com.xinnet.mms.login.dao.EmpDao;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.shopcart.dao.ShopcartDao;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.CustomerType;
/**
 * 
 * @author 王湛智
 *
 */
@Controller
@RequestMapping("/cart")
public class ShopCartController {
	
	@Autowired
	private ShopCartService shopCartService;
	@Autowired
	private CustomerManageService customerManageService;
	
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private AreaService areaService;
	@Autowired
	private EmpDao empDao;
	ObjectMapper mapper = new ObjectMapper();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 
	 * 功能描述：显示购物车页面
	 * 
	 * @author 王湛智
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/showPage/{pageNow}")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public String showShopCartPage(PageView<Customer> pageView , Customer customer,  HttpServletRequest request,HttpSession session, Model model) throws Exception {
		Emp currentUser=(Emp) request.getSession().getAttribute("currentUser");
		// 客户管理查询条件：所属人的部门组织Ztree Json
		String deptJson = AppGlobalContainer.deptIdToDeptJsonMap.get(currentUser.getId());
		if(deptJson==null){
			deptJson = "["
					+ deptService.getDeptTreeByDeptId(currentUser.getId()) + "]";
			AppGlobalContainer.deptIdToDeptJsonMap.put(currentUser.getId(), deptJson);
		}
		model.addAttribute("deptJson", deptJson);

		// 客户管理查询条件：所属区域
		List<Area> parentAreaList = areaService.getAreaOfClassA();
		model.addAttribute("parentAreaList", parentAreaList);

		List<Area> childAreaList = areaService.getAreaOfClassB();
		model.addAttribute("childAreaList", childAreaList);
		
		//查询该员工的所有已接受客户
		
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}
		}
		//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		customer.setCustomerType(CustomerManage.CUSTOMER_SHOP_CART);
		customer.setCustomState(1);
		
		String nolinkedDay1 = customer.getNolinkedDay1();
		String nolinkedDay2 = customer.getNolinkedDay2();
		if(nolinkedDay1!=null&&!"".equals(nolinkedDay1)&&nolinkedDay2!=null&&!"".equals(nolinkedDay2)){
			
			Calendar c1 = Calendar.getInstance();
			c1.setTime(new Date());
			int int1 = -Integer.valueOf(nolinkedDay1);
			int int2 = -Integer.valueOf(nolinkedDay2);
			c1.add(Calendar.DATE,int1);
			
			Calendar c2 = Calendar.getInstance();
			c2.setTime(new Date());
			c2.add(Calendar.DATE,int2);
			
			nolinkedDay1 = sdf.format(c1.getTime());
			nolinkedDay2 = sdf.format(c2.getTime());
			customer.setNolinkedDay1(nolinkedDay1);
			customer.setNolinkedDay2(nolinkedDay2);
		}
		if ((!role.getName().equals("总经理") && !role.getName().equals("副总经理") && role.getName().indexOf("总监")<0) || "1".equals(customer.getRemark())) {
			pageView=customerManageService.queryCustomer(pageView, customer);
		} else {
			pageView = new PageView<Customer>();
			pageView.setRecords(new ArrayList<Customer>());
		}
		
		
		if(customer.getRegionalId()!=null ||"".equals(customer.getRegionalId())) {
			Area a = areaService.getParentIdByAreaId(customer.getRegionalId());
			model.addAttribute("parentRegionalId",a.getParentId());
		}
		model.addAttribute("pageView", pageView);
		model.addAttribute("customer", customer);
		@SuppressWarnings("unchecked")
		List<Customer> customerList=pageView.getRecords();
		CustomerTypeEnmu[] customerTypeEnmuArray = CustomerTypeEnmu.values();
		request.setAttribute("customerTypeEnmuArray", customerTypeEnmuArray);

		request.setAttribute("customerList", customerList);
		return "market/customer/customer_shopcart";
		
	}
	
	
	/**
	 * 
	 * 功能描述：显示购物车信息
	 * 
	 * @author 王志军
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/showInfo/{pageNow}")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public String showShopCartInfo(PageView<Customer> pageView , Customer customer,  HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		
		
		customer.setCustomerType(CustomerManage.CUSTOMER_SHOP_CART);
		
		customer.setCustomType(CustomerManage.CUSTOMER_SHOP_CART);
		
		pageView=customerManageService.queryCustomer(pageView, customer);
		model.addAttribute("pageView", pageView);
		@SuppressWarnings("unchecked")
		List<Customer> customerList=pageView.getRecords();
		request.setAttribute("customerList", customerList);
		PrintWriter pw = response.getWriter();
		pw.print(mapper.writeValueAsString(customerList));
		return null;
		
	}
	
	/**
	 * 
	 * 功能描述：显示会员的购物车信息
	 * 
	 * @author 王湛智
	 * 
	 * @param request
	 * @param response
	 * @param cusId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/showCart/{pageNow}")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String showAllCustomer(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response,String cusId) throws Exception {
		List<Customer> cartList=shopCartService.getShopCartByCusIdPackageToCustomer(cusId);
		request.getSession().setAttribute("cusId", cusId);
		
		PrintWriter pw = response.getWriter();
		
		pw.print(mapper.writeValueAsString(cartList));
		return null;
	}
	
	@RequestMapping("/getAddShopCartCount")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public void getAddShopCartCount(HttpServletRequest request,HttpSession session,HttpServletResponse response) throws Exception {
		Emp currentUser=(Emp) request.getSession().getAttribute("currentUser");
		Customer customer=new Customer();
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			customer.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == customer.getEmpno() || "".equals(customer
						.getEmpno()))) {
			if (null == customer.getDeptId() || "".equals(customer.getDeptId())) {
				customer.setDeptId(currentUser.getId());
			}
		}//获取当前登录人的角色
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			customer.setDeptId(null);
		}
		PrintWriter pw = response.getWriter();
		customer.setCustomState(1);
		Integer count  = customerManageService.addShopCartCustomerCount(customer);
		pw.print(count);
	}
	/**
	 * 王志军
	 * 2016-9-8
	 * @param request
	 * @param session
	 * @param response
	 * @param pageView
	 * @param shopCart
	 * @throws Exception
	 */
	@RequestMapping("/showShopCart")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public void showShopCart(HttpServletRequest request,HttpSession session,HttpServletResponse response,PageView<Map<String,Object>> pageView,ShopCart shopCart) throws Exception {
		Emp currentUser=(Emp) request.getSession().getAttribute("currentUser");
		// 设置查看客户（客户负责人）
		// 如果是部门负责人 则客户负责人由前台传入
		if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_NO)) {
			shopCart.setEmpId(currentUser.getEmpno());
		} else if (null != currentUser.getIsResponsible()
				&& currentUser.getIsResponsible().equals(
						CustomerManage.IS_RESPONSIBLE_YES)
				&& (null == shopCart.getEmpno() || "".equals(shopCart
						.getEmpno()))) {
			if (null == shopCart.getDeptId() || "".equals(shopCart.getDeptId())) {
				Emp emp = new Emp();
				emp.setId(currentUser.getId());
				List<String> empList = empDao.getEmpNoList(emp);
				shopCart.setEmpnoList(empList);
			}
		}//获取当前登录人的角色
		Integer rows = Integer.valueOf(request.getParameter("rows"));
		pageView.setPageNow(Integer.valueOf(request.getParameter("page")));
		shopCart.setLimitTop(pageView.getFirstResult());
		shopCart.setLimitDown(rows);
		Role role = (Role) session.getAttribute("role");
		//总经理与副总经理拥有最高查询权限 无需关联部门关系表来进行权限控制 所以将部门ID置为null
		if (role.getName().equals("总经理") || role.getName().equals("副总经理")) {
			shopCart.setDeptId(null);
			shopCart.setEmpnoList(null);
		}
		PrintWriter pw = response.getWriter();
		List<ShopCart> customerList = customerManageService.queryShopCartCustomer(shopCart);
		int totalCount = shopCart.getRowCount();
		Integer pageCount = (totalCount + rows - 1) / rows;
		pageView.setRowCount(totalCount);
	    pageView.setPageCount(pageCount);
	    pageView.setRecords(customerList);
	    String str1 = mapper.writeValueAsString(pageView);
		pw.print(str1);
	}
	
	/**
	 * 
	 * 功能描述：打开购物车商品页面
	 * 
	 * @author 王湛智
	 * 
	 * @param request
	 * @param response
	 * @param cusId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/openCartPage")
	public String openCustomer() {
		return "market/util/cart";
	}
}
